package com.cadre.common.utils.common;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
/* loaded from: RedisUtils.class */
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> valueOperations;
    @Resource(name = "redisTemplate")
    private HashOperations<String, String, Object> hashOperations;
    @Resource(name = "redisTemplate")
    private ListOperations<String, Object> listOperations;
    @Resource(name = "redisTemplate")
    private SetOperations<String, Object> setOperations;
    @Resource(name = "redisTemplate")
    private ZSetOperations<String, Object> zSetOperations;
    public static final long DEFAULT_EXPIRE = 86400;
    public static final long NOT_EXPIRE = -1;

    public void set(String key, Object value, long expire) {
        this.valueOperations.set(key, toJson(value));
        if (expire != -1) {
            this.redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value) {
        set(key, value, DEFAULT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = (String) this.valueOperations.get(key);
        if (expire != -1) {
            this.redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        if (value == null) {
            return null;
        }
        return (T) fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return (T) get(key, clazz, -1);
    }

    public String get(String key, long expire) {
        String value = (String) this.valueOperations.get(key);
        if (expire != -1) {
            this.redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, -1);
    }

    public void delete(String key) {
        this.redisTemplate.delete(key);
    }

    private String toJson(Object object) {
        if ((object instanceof Integer) || (object instanceof Long) || (object instanceof Float) || (object instanceof Double) || (object instanceof Boolean) || (object instanceof String)) {
            return String.valueOf(object);
        }
        return JSON.toJSONString(object);
    }

    private <T> T fromJson(String json, Class<T> clazz) {
        return (T) JSON.parseObject(json, clazz);
    }
}
